package com.youpingou.filter;

import com.youpingou.config.PathProperties;
import com.youpingou.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Order(-1)
public class JWTFilter2 implements GlobalFilter {

    @Autowired
    private PathProperties pathProperties;


    public boolean isAllowPths(String url){
        // 1. 定义返回的变量
        // 默认拦截
        boolean flag = true;
        // 2. 获取yml中的集合
        List<String> list = pathProperties.getAllowPaths();
        // 3. 判断url是否在集合中
        for(String s:list){
            // 当yml中的路径在url中找到了，就放行
            if(url.indexOf(s)!=-1){
                flag=false;
                break;
            }
        }
        // 4. 在--返回false
        // 5. 不在-返回true，执行run方法
        return flag;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String url = exchange.getRequest().getURI().getPath();
        System.out.println(url);
        // 1 判断URL
        if(!isAllowPths(url)){
            System.out.println("无需登录，直接放行");
            return chain.filter(exchange);
        }
        // 2.获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        // 3.获取authorization参数
        String token = params.getFirst("authorization");

        List<String> tokens = exchange.getRequest().getHeaders().get("authorization");

        // 4判断是否为空
        if(tokens!=null&&(tokens.size()==1)){
            // 5 解析token
            Claims claims = JWTUtil.parseToken(tokens.get(0), "admin");
            //6 判断解析是否成
            if(claims!=null){
                //7 成功了，放行
                return chain.filter(exchange);
            }
        }
        // 8.拦截
        // 8.1.禁止访问，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 8.2.结束处理
        return exchange.getResponse().setComplete();

    }
}
